#!/usr/bin/env bash

Error_out(){
	cat <<- EOF
	USAGE: ./modify inject blobs [/path/to/rom] [boardname]
	Example: ./modify inject blobs x230_12mb.rom x230_12mb

	"boardname" must be one of:
	$(listboards)
	EOF

	exit 1
}

listboards() {
	for boarddir in resources/coreboot/*; do
		if [ ! -d "${boarddir}" ]; then continue; fi
		board="${boarddir##resources/coreboot/}"
		board="${board%/}"
		printf '%s\n' "${board##*/}"
	done
}

# This function tries to determine the board from the filename of the rom.
# It will only succeed if the filename is not changed from the build/download
Detect_board(){
	filename=$(basename ${rom})
	case ${filename} in
		grub_*)
		board=$(cut -d '_' -f2-3 <<<${filename})
		;;
		seabios_grubfirst_*|seabios_withgrub_*)
		board=$(cut -d '_' -f3-4 <<<${filename})
		;;
		*)
		return 1
	esac	

	if [ -d "resources/coreboot/${board}/" ]; then
		printf '%s\n' "${board}"
	else
		return 1
	fi
}

Patch(){
echo "patching"
board_short=${board%%_*mb}
set -- "resources/coreboot/${board}/config/*"
. ${1} 2>/dev/null
. "resources/coreboot/${board}/board.cfg"

	if [ "$CONFIG_HAVE_MRC" = "y" ]; then
		printf 'adding mrc\n'
		./coreboot/default/util/cbfstool/cbfstool ${rom} add -f mrc/haswell/mrc.bin -n mrc.bin -t mrc || exit 1
	fi

	if [ "${CONFIG_HAVE_ME_BIN}" = "y" ]; then
		printf 'adding intel management engine\n'
		./coreboot/default/util/ifdtool/ifdtool -i me:blobs/${board_short}/me.bin ${rom} -O ${rom} || exit 1
	fi
}

if [ ! -z ${1+x} ]; then
	rom=${1}
else
	printf 'no rom specified\n'
	Error_out
	
fi

if [ ! -z ${2+x} ]; then
	board=${2}
else
	board=$(Detect_board) || \
	printf 'no board specifid' \
	Error_out
	
fi

if [ ! -d "resources/coreboot/${board}/" ]; then
	printf "board ${board} not found\n"
	Error_out
fi

if [ ! -d coreboot ]; then
	printf "downloading coreboot\n"
	./download coreboot
fi

if [ ! -f "coreboot/default/util/ifdtool/ifdtool" ]; then
printf "building ifdtool from coreboot\n"
( cd coreboot/default/util/ifdtool && make )
fi

if [ ! -f "coreboot/default/util/cbfstool/cbfstool" ]; then
printf "building cbfstool from coreboot\n"
( cd coreboot/default/util/cbfstool && make )
fi

./download blobs ${board} && Patch
